<template>
  <div class="main">
    <div class="spacer" style="padding-top: calc(var(--space) * 0.5)"></div>
    <div class="wrapper bread-crumb">
      <nuxt-link :to="localePath('/')">{{$t('homePage')}}</nuxt-link>
      <i class="sight-icon-chevron-right"></i>
      <nuxt-link :to="localePath(`/posts?tag=${tag}`)">{{ tag ? `${tag} ${$t('relatedArticle')}` : $t('allArticle')}}</nuxt-link>
      <template v-if="keyword">
        <i class="sight-icon-chevron-right"></i>
        <nuxt-link :to="localePath(`/posts?tag=${tag}&keyword=${keyword}`)">{{ $t(searchResult) }}</nuxt-link>
      </template>
    </div>
    <div class="spacer" style="padding-top: calc(var(--space) * 0.5)"></div>

    <div class="wrapper wiss">
      <div class="side">
        <div class="content">
          <div class="cards">
            <div class="container">
              <div class="card lottie">
                <div ref="lottie" class="lottie-animate"></div>
                <div class="lottie-content">
                  <h2 class="title">{{ $t('master') }}.</h2>
                  <p class="summary">
                    {{ $t('workIntroducePrefix')
                    }}<span class="tips-info" :title="`${$t('endOf')} ${endDate}`"
                      >{{ workYears }}{{ $t('year') }}</span
                    >{{ $t('workIntroduceSuffix') }}
                  </p>
                </div>
              </div>
              <div class="topic">
                <nuxt-link class="topic-title" :to="localePath('/posts')">{{ $t('topic') }}</nuxt-link>
                <div class="topic-list">
                  <div class="topic-card" @click="goToTopic('vue')">
                    <div><img :src="require('@/assets/symbol/vue.svg')" alt="" /></div>
                    <p>VueJS</p>
                  </div>
                  <div class="topic-card" @click="goToTopic('react')">
                    <div><img :src="require('@/assets/symbol/react.svg')" alt="" /></div>
                    <p>ReactJs</p>
                  </div>
                  <div class="topic-card" @click="goToTopic('node')">
                    <div><img :src="require('@/assets/symbol/node.svg')" alt="" /></div>
                    <p>NodeJs</p>
                  </div>
                  <div class="topic-card" @click="goToTopic('webpack')">
                    <div><img :src="require('@/assets/symbol/webpack.svg')" alt="" /></div>
                    <p>WebPack</p>
                  </div>
                  <div class="topic-card" @click="goToTopic('visual')">
                    <div>
                      <img :src="require('@/assets/symbol/visualize.svg')" alt="" />
                    </div>
                    <p>Visualize</p>
                  </div>
                  <div class="topic-card" @click="goToTopic('app')">
                    <div><img :src="require('@/assets/symbol/hybrid.svg')" alt="" /></div>
                    <p>Hybrid</p>
                  </div>
                </div>
              </div>
              <div class="search">
                <s-input 
                :placeholder="$t('placeholder')" 
                :value="keyword" @search="search" 
                @input="val=>keyword = val">
              </s-input>
              </div>
              <div class="site-info">
                <div class="info">
                  <p>{{ $t('stationState') }}<span :title="`${$t('since')} ${startDate}`" class="tips-info">{{ count }}</span>{{ $t('day') }} </p>
                </div>
                <p class="bonus">
                  {{ $t('advertising') }}
                  <a href="mailto:1148606675@qq.com">
                    <i class="sight-icon-mail"></i>1148606675@qq.com
                  </a>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div ref="scroll" class="right">
        <div class="cards">
          <div v-for="(post,i) in articles" :key="i" class="cards__column">
            <div class="card card-section container" @click="goToArticle(post.slug)">
              <div class="card__aside">
                <div class="card__figure">
                  <div v-if="post.image" class="card__image">
                    <img
                      fit="cover"
                      loading="lazy"
                      :src="$config.STATIC_BASE + post.image + $config.STATIC_CLIP"
                      :alt="post.title"
                    />
                  </div>
                </div>
              </div>
              <div class="card__body">
                <div class="card__header">
                <div class="card__title">{{post.title}}</div>
                <div class="card__subtitle">
                  {{post.description}}
                </div>
              </div>
              <div class="card__footer">
                <div class="author">
                  <div class="avatar">
                    <img :src="$config.STATIC_BASE + '/author/'+ post.author.avatar" :alt="post.author.name" />
                  </div>
                  <a target="_blank" :href="post.author.link || '#' " class="name">@{{post.author.name}}</a>
                </div>
                <div class="date">{{formatDate(post.createdAt)}}</div>
              </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="!articles.length"  class="card card-section container">
          <div class="no-data">
            <p v-if="/^[\u4e00-\u9fa5]/.test(keyword)">🙏拜托～类MongoDB中文检索真的很差</p>
            <p v-else>真的一滴都没有了~</p>
          </div>
        </div>
        <div v-if="articles.length === 20" class="card change" @click="nextPage">
          <p>{{$t('change')}}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import lottie from 'lottie-web'
import SInput from '@/packages/input/src'
import astronaut from '@/assets/animate/astronaut.json'
export default {
  name: 'Article',
  components: {
    SInput,
  },
  scrollToTop:true,
  async asyncData({$content,query}) {
    const { page, keyword = '', tag = '' } = query
    const skip = page  ? 20 * (query.page -1) : 0;
    let where = {
       publish: 1,
    }
    if(tag){
      where = {
        ...where,
        tag:{
          $contains:tag
        },
      }
    }
    const workYears = dayjs().diff('2019-03-01', 'year')
    const endDate = dayjs().format('YYYY/MM/DD')
    const startDate = '2019-12-01'
    const count = dayjs().diff(startDate, 'day')
    const req = keyword ?
      $content('articles').where(where).without(['body']).sortBy('createdAt','desc').limit(100).fetch()
      : $content('articles').where(where).without(['body']).sortBy('createdAt','desc').skip(skip).limit(20).fetch()
    const articles = await req
    let searchResult = ''
    if(tag) {
      searchResult =  tag + '相关文章 '
    }
    if(keyword){
      searchResult += keyword + '的搜索结果'
    }
    return {
      workYears,
      endDate,
      startDate,
      count,
      articles: keyword ? articles.filter(v=> new RegExp(keyword,'i').test(v.title)) : articles,
      keyword,
      tag,
      searchResult
    }
  },
  head() {
    const {tag,keyword} = this.$route.query
    let title = !keyword && !tag ? '这是很长很好的一生' : ''
    if(tag) {
      title =  tag + '相关文章 '
    }
    if(keyword){
      title += keyword + '的搜索结果'
    }
    return {
      title,
      meta: [
        { hid: 'description', name: 'description', content: '汇集SPA单页应用、SSR服务端渲染、WebPack/Vite打包配置、小程序开发、前端最佳实践以及前端框架源码解读等文章。'}
      ]
    }
  },
  watchQuery:['tag','page','keyword'],
  mounted() {
    this.animateLottie()
  },
  methods: {
    lottieReady() {
      this.lottieIsReady = true
    },
    animateLottie() {
      this.initLottie(astronaut)
    },
    initLottie(data, loop = true) {
      const lottieEl = this.$refs.lottie
      this.lottie = lottie.loadAnimation({
        container: lottieEl,
        renderer: 'svg',
        loop,
        autoplay: true,
        animationData: data,
      })
    },
    nextPage(){
      const { path, query} = this.$route
      this.$router.push({
        path,
        query:{
          ...query,
          page: query.page ? query.page + 1 : 2
        }
      })
    },
    goToArticle(slug){
      this.$router.push(this.localePath(`/article/${slug}`))
    },
    search(kw){
       const { path, query} = this.$route
      this.$router.push({
        path:this.localePath(path),
        query:{
          ...query,
          page: 1,
          keyword: kw
        }
      })
    },
    goToTopic(tag){
       const { path, query} = this.$route
      this.$router.push({
        path:this.localePath(path),
        query:{
          ...query,
          page: 1,
          tag,
          keyword:''
        }
      })
    },    
    formatDate(date) {
      return dayjs(date).format('YYYY/MM/DD HH:mm:ss')
    },
  },
}
</script>
<style lang="scss" scoped>
.cards {
  max-width: 720px;
  margin-left: auto;
}
.no-data{
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}
.side {
  flex: 1;
  min-width: 350px;
  margin-right: var(--gap);
  .content {
    position: sticky;
    top: calc(var(--header-height) + var(--space-4x));
    width: 100%;
    .lottie {
      text-align: center;
      padding: 0;
      position: relative;
      overflow: hidden;
    }
    .lottie-animate{
      margin-top: var(--space-mini-negative);
    }
    .lottie-content{
      width: 100%;
      position: absolute;
      left: 0;
      bottom: var(--space-mini);
    }
  }
  .cards {
    max-width: 400px;
    & > * + * {
      margin-top: var(--gap);
    }
  }
  .topic {
    padding: var(--space-mini) 0;
    .topic-title{
      font-weight: bold;
    }
  }
  .tips-info{
    color: var(--highlight-purple);
    cursor: help;
  }
  .topic-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-top: var(--space-4x);
    .topic-card {
      cursor: pointer;
      display: flex;
      margin: var(--space-gap-half) 0;
      justify-content: center;
      flex-direction: column;
      text-align: center;
      p{
        font-weight: bold;
        font-size: 0.75em;
      }
    }
  }
  .site-info {
    margin: var(--space-mini) 0;
    .bonus {
      margin-top: var(--space-4x);
    }
  }
}
.right{
  flex: 2;
  .cards{
    column-count: 2;
    column-gap: var(--gap);
    .cards__column{
      page-break-inside: avoid;
      overflow: hidden;
    }
    .card{
      margin-bottom: var(--gap);
      display: flex;
      padding: 0;
      .card__header{
        margin: 0;
      }
      .card__body{
        margin: var(--space-gap);
      }
    }
  }
  .card__figure{
    img{
      width: 346px;
      height: 171px;
      object-fit: cover;
    }
  }
}
.search {
  padding-bottom: var(--space-mini);
}
.bread-crumb {
  margin: auto;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  color: var(--accents-5);
}
.bread-crumb i {
  margin: 0 var(--space-2x);
}
.bread-crumb a{
  color: inherit;
}
.bread-crumb a:hover{
  color: var(--foreground);
}
.title {
  font-size: 1rem;
  line-height: 1.5;
  margin-bottom: var(--space-2x);
}
.sub-title {
  font-size: 0.875rem;
  line-height: 1.3;
}
.summary {
  margin-top: var(--space-2x);
}
.card__footer{
  display: flex;
  color: var(--accents-5);
  font-size: 0.75rem;
  margin-top: var(--space-4x);
      align-items: center;
    justify-content: space-between;
}
.author{
  display: flex;
  align-items: center;
  .avatar {
    display: flex;
    width: 30px;
    border-radius: 5px;
    overflow: hidden;
    img {
      width: 100%;
      object-fit: cover;
    }
  }
  .name{
    margin-left: var(--space-2x);
  }
}
.date {
  font-family: var(--font-mono);
}
.change{
  margin-top: var(--gap);
  padding: var(--space-2x);
  text-align: center;
}

@media screen and (max-width: 900px) {
  .cards{
    margin: auto;
  }
  .side {
    margin: 0;
    min-width:0;
    .topic {
      text-align: center;
      order: 2;
    }
    .topic-list {
      .topic-card {
        width: 30%;
        align-items: center;
      }
    }
  }
  .side .search {
    order: 1;
  }
  .right{
    .cards{
      column-count: auto;
      column-gap: auto;
    }
    .card__figure{
      img{
        width: 100%;
        height: 198px;
      }
    }
  }
}
@media (prefers-color-scheme: dark) {
  .side{
    .content{
      .lottie{
        background: var(--foreground);
        color: var(--background);
        filter: invert(1);
      }
    }
  }
  .title {
    color: var(--background);
  }
  .sub-title {
    color: var(--background);
  }
}
[theme='dark'] {
  .side{
    .content{
      .lottie{
        background: var(--foreground);
        filter: invert(1);
      }
    }
  }
  .title {
    color: var(--background);
  }
  .sub-title {
    color: var(--background);
  }
}

</style>
